﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using RelationTextBox;
using System.Diagnostics;
using System.Threading;
using System.Globalization;
using System.Reflection;

namespace ExBug
{
    public partial class BugetFrm : FrmTreeRezumat
    {

        TreeNode tnRoot = new TreeNode();
        private Int16 AnCurent = 0;
        private Boolean init_form = true;
        public BugetFrm(ModuleClass mInfo)
            : base(mInfo)
        {
            InitializeComponent();
            localTree = BugetTV;
            workConnString = "ESRPConnectionString";
            txtRoot = "Clasificatie Functionala                        ";
            ColoanaParinte = "AAParinte";
            diviziuneMonedaSursaBindingSource.List.Add(new DiviziuneMonedaSursa("Lei", 0));
            diviziuneMonedaSursaBindingSource.List.Add(new DiviziuneMonedaSursa("Mii lei", 1));

            eSRPDataSet.Buget.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            eSRPDataSet.Buget.DenumireColumn.DefaultValue = "";
            eSRPDataSet.Buget.MultiAnualColumn.DefaultValue = false;
            eSRPDataSet.Buget.RectificativColumn.DefaultValue = false;
            numeMacheta = Text;
            BugetTV.Scroll += new xTreeView.ScrollEventHandler(BugetTV_Scroll);
            
        }

        void BugetTV_Scroll(object sender, xTreeView.ScrollEventArgs e)
        {
            /// pozitioneaza gridul pe aeiasi pozitie vizibila
            /// ca si treeview-ul
            /// 
            DataGridViewRow dv = ((NodeInfo)e.Top.Tag).GridRowNo as DataGridViewRow;
            if(dv!=null && dv.Visible)
                BugetDGV.FirstDisplayedScrollingRowIndex =dv.Index;

        }

        private void BugetFrm_Load(object sender, EventArgs e)
        {
            
            this.bugetTableAdapter.Connection = DeschideConexiune(workConnString);
            this.jurnaleTableAdapter.Connection = this.bugetTableAdapter.Connection;
            this.jurnaleTableAdapter.Fill(eSRPDataSet.Jurnale, ModuleInfo.CodUnitate);
            this.listBndSourceMain.Add(articoleAliniateBindingSource);
            this.listTableAdaptor.Add(articoleAliniateTableAdapter.Adapter);

            this.BugetTV.Nodes.Clear();
            tnRoot.Text = txtRoot;
            tnRoot.Tag = new NodeInfo("N/A");
            tnRoot.Name = "N/A";
            tnRoot.NodeFont = new Font(BugetTV.Font, FontStyle.Bold);

            this.BugetTV.Nodes.Add(tnRoot);
            ColoanaPK = "ArtAl";
            ColoanaNume = "Denumire";
            JurnalCB_SelectedIndexChanged(this, null);
            LoadSetup(bugetTableAdapter.Connection);
            InchideConexiune(bugetTableAdapter.Connection);
            Text = numeMacheta + " - " + ((BugetTV.SelectedNode != null) ? BugetTV.SelectedNode.Text : "");
            eSRPDataSet.ArticoleAliniate.AAParinteColumn.DefaultValue = Convert.ToInt32(0);
            //BugetDGV.Rows.Add(bugetBindingSource.Count);
            init_form = false;
            AddButton("Genereaza NC", global::ERPStudio.Properties.Resources.salvare1, GenereazaNC, ToolStripItemAlignment.Right, true);
            AddButton("Setaza data", global::ERPStudio.Properties.Resources.info, Initializare, ToolStripItemAlignment.Right, false);
            DiviziuneMonetaraCB.SelectedIndex = 0;
        }

        public void LoadSetup(SqlConnection sqlConn)
        {
            Object ret = GetSetupValue("ExBugSetup", "AnulCurent", ModuleInfo.CodUnitate, sqlConn);
            if (ret == null)
            { 
                //adauga o inregistrare in exbug pentru ca unitatea nu e configurata
                SqlCommand cmd = new SqlCommand("INSERT INTO [ExBugSetup]([CompartimentSpecialitate],[OrdonatorCredite],[CodUnitate],[AnCurent])"+
                "VALUES('',''," + ModuleInfo.CodUnitate.ToString() + "," + DateTime.Now.Year.ToString() + ")", sqlConn);
                cmd.ExecuteNonQuery();
                ret = GetSetupValue("ExBugSetup", "AnCurent", ModuleInfo.CodUnitate, sqlConn);
            }
            
            AnCurent = (Int16)ret;
            eSRPDataSet.Buget.DataSfarsitColumn.DefaultValue = new DateTime(AnCurent, 12, 31);

            //daca nu au fost introduse jurnale atunci nu afiseaza combo de jurnale;
            if (eSRPDataSet.Jurnale.Count == 0)
            {
                JurnalL.Visible = false;
                JurnalCB.Visible = false;
                eSRPDataSet.Buget.IDJurnalColumn.DefaultValue = 0;
            }
            else
            {
                // trece toate bugetele pe primul jurnal
                SqlCommand cmd = new SqlCommand("SELECT Count(*) FROM [Buget] WHERE [IDJurnal]=0", sqlConn);
                Object cateJurnZero = cmd.ExecuteScalar();

                if (cateJurnZero != null && Convert.ToInt32(cateJurnZero)!=0)
                { 
                    //deci sunt care nu sunt pe 0
                    MessageBox.Show("Toate inregistrarile care nu au un jurnal setat vor fi trecute pe primul jurnal!(" + eSRPDataSet.Jurnale.Rows[0]["Denumire"].ToString() + ")",
                        "Avertisment",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);

                    SqlCommand cmd1 = new SqlCommand("UPDATE [Buget] SET [IDJurnal] = " + eSRPDataSet.Jurnale.Rows[0]["IDJurnal"].ToString() + " WHERE [IDJurnal]=0", sqlConn);
                    cmd1.ExecuteScalar();
                }
            }
        }
        /// <summary>
        /// functia care incarca coloanele
        /// </summary>
        private void LoadColumns(Boolean total)
        {
            if (JurnalCB.SelectedValue == null)
                return;
            SqlCommand cmd = new SqlCommand("SELECT DISTINCT Data FROM [BugetCentralizator] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString() +
                (total?"":(" AND [IDJurnal]=" + JurnalCB.SelectedValue.ToString())),
                DeschideConexiune(workConnString));
            SqlDataReader dataReader = cmd.ExecuteReader();
            ///aici gridul nu are nici un rand
            ///
            AddColumn("Art./Alin.", true);
            AddColumn("Total",true);
            while (dataReader.Read())
            {
                AddColumn(((DateTime)dataReader["Data"]).ToShortDateString(),false);
            }
            dataReader.Close();
            InchideConexiune(cmd.Connection);
        }

        private void AddColumn(String newDate,Boolean readOnly)
        {
            DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
            col.HeaderText = newDate;
            col.Name = col.HeaderText;
            col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            col.SortMode = DataGridViewColumnSortMode.NotSortable;
            col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            col.DefaultCellStyle.Format = "N2";
            col.ReadOnly = readOnly;
            if (readOnly)
            {
                col.DefaultCellStyle.BackColor = System.Drawing.SystemColors.InactiveBorder;
                col.HeaderCell.Style.BackColor = System.Drawing.SystemColors.InactiveBorder;
            }
            BugetDGV.Columns.Add(col);
        
        }

        private void LoadRowInfo(DateTime data,Int32 idJurn,String colName)
        {

            SqlCommand cmd = new SqlCommand("SELECT * FROM [BugetCentralizator] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString() + 
                ((idJurn==-1)?"":(" AND IDJurnal = " + idJurn.ToString())) + " AND Data=@Data",
                DeschideConexiune(workConnString));
            cmd.Parameters.Add(new SqlParameter("Data",data));
            SqlDataReader dataReader = cmd.ExecuteReader();

            while (dataReader.Read())
            {
                TreeNode[] ret = BugetTV.Nodes.Find(dataReader["ArtAl"].ToString(),true);
                if (ret != null && ret.Length>0)
                {
                    ((DataGridViewRow)((NodeInfo)ret[0].Tag).GridRowNo).Cells[colName].Value = dataReader["Suma"];
                }
            }
            dataReader.Close();
            InchideConexiune(cmd.Connection);
        }

        private void LoadRowTotalInfo(Int32 idJurn, String colName)
        {

            SqlCommand cmd = new SqlCommand("SELECT ArtAl," + 
                ((idJurn==-1)?"":"IDJurnal,")+"CodUnitate,Sum(Suma) AS Suma FROM [BugetCentralizator] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString() +
                ((idJurn==-1)?"":(" AND IDJurnal = " + idJurn.ToString())) + " GROUP BY ArtAl," +
                ((idJurn == -1) ? "" : "IDJurnal,") + "CodUnitate",
                DeschideConexiune(workConnString));
            SqlDataReader dataReader = cmd.ExecuteReader();

            if (!dataReader.HasRows)
            {
                foreach (DataGridViewRow dr in BugetDGV.Rows)
                    dr.Cells[colName].Value = 0;
            }
            else
                while (dataReader.Read())
                {
                    TreeNode[] ret = BugetTV.Nodes.Find(dataReader["ArtAl"].ToString(), true);
                    if (ret != null && ret.Length > 0)
                    {
                        ((DataGridViewRow)((NodeInfo)ret[0].Tag).GridRowNo).Cells[colName].Value = dataReader["Suma"];
                    }
                }
            dataReader.Close();
            InchideConexiune(cmd.Connection);
        }


        private void Initializare(object sender, EventArgs e)
        {
            InitializareBugetFrm frm = new InitializareBugetFrm(ModuleInfo);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                AddColumn(frm.monthCalendar.SelectionStart.ToShortDateString(),false);
                init_form = true;
                foreach (DataGridViewRow dr in BugetDGV.Rows)
                    dr.Cells[frm.monthCalendar.SelectionStart.ToShortDateString()].Value = 0;
                init_form = false;
            }
        }

        private void BugetDGV_Scroll(object sender, ScrollEventArgs e)
        {
            if (e.ScrollOrientation == ScrollOrientation.VerticalScroll)
            {
                if (BugetDGV.Rows[BugetDGV.FirstDisplayedScrollingRowIndex].Tag!=null)
                    BugetTV.TopNode = ((TreeNode)BugetDGV.Rows[BugetDGV.FirstDisplayedScrollingRowIndex].Tag);
            }
        }

        private void BugetTV_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
        {
            ///nu se permite restrangerea nodurilor tree-ului
            ///deocamdata - la aceasta versiune
            e.Cancel = true;
        }

        private void BugetTV_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //if (e.Action != TreeViewAction.Unknown)
            //   return;
            DataGridViewRow dv = ((NodeInfo)e.Node.Tag).GridRowNo as DataGridViewRow;
            if (dv != null)
            {
                BugetDGV.CurrentCell = dv.Cells[0];
            }
            e.Node.TreeView.SelectedNode = e.Node;

        }

        private void BugetDGV_SelectionChanged(object sender, EventArgs e)
        {
            TreeNode tn = BugetDGV.Rows[BugetDGV.CurrentCell.RowIndex].Tag as TreeNode;
            if (tn != null)
            {
                tn.TreeView.SelectedNode = tn;
            }
        }

        private void BugetDGV_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (BugetDGV.Columns[e.ColumnIndex].HeaderText == "Total")
                return;
            if (!init_form)
            {
                
                SqlCommand cmd = new SqlCommand("UpdateBuget", DeschideConexiune(workConnString));
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("CodUnitate",ModuleInfo.CodUnitate));
                cmd.Parameters.Add(new SqlParameter("IDJurnal", Convert.ToInt32(JurnalCB.SelectedValue)));
                cmd.Parameters.Add(new SqlParameter("Data", Convert.ToDateTime(BugetDGV.Columns[e.ColumnIndex].HeaderText)));
                cmd.Parameters.Add(new SqlParameter("ArtAl", ((TreeNode)BugetDGV.Rows[e.RowIndex].Tag).Name));
                cmd.Parameters.Add(new SqlParameter("Suma", Convert.ToDecimal(BugetDGV[e.ColumnIndex,e.RowIndex].Value)));
                cmd.ExecuteNonQuery();
                ///reciteste informatiile din coloana
                ///
                init_form = true;
                LoadRowInfo(Convert.ToDateTime(BugetDGV.Columns[e.ColumnIndex].HeaderText),
                    Convert.ToInt32(JurnalCB.SelectedValue), BugetDGV.Columns[e.ColumnIndex].HeaderText);
                LoadRowTotalInfo(Convert.ToInt32(JurnalCB.SelectedValue), "Total");
                init_form = false;
                InchideConexiune(cmd.Connection);
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
             JurnalCB.Enabled = !TotalCB.Checked;
             if (TotalCB.Checked)
             {
                 init_form = true;
                 Cursor.Current = Cursors.WaitCursor;
                 SqlConnection conn = DeschideConexiune(workConnString);
                 BugetDGV.Columns.Clear();
                 LoadColumns(true);

                 LoadTreeAndGrid(tnRoot, conn, ModuleInfo.CodUnitate.ToString(), BugetDGV);
                 LoadRowTotalInfo(-1, "Total");
                 foreach (DataGridViewColumn col in BugetDGV.Columns)
                 {
                     if (col.HeaderText != "Total" && col.HeaderText != "Art./Alin.")
                         LoadRowInfo(Convert.ToDateTime(col.HeaderText), -1, col.HeaderText);
                 }
                 InchideConexiune(conn);
                 Cursor.Current = Cursors.Default;
                 BugetDGV.ReadOnly = true;
                 init_form = false;
             }
             else
             {
                 BugetDGV.ReadOnly = false;
                 JurnalCB_SelectedIndexChanged(this, null);
             }
        }

        private void JurnalCB_SelectedIndexChanged(object sender, EventArgs e)
        {
            init_form = true;
            Cursor.Current = Cursors.WaitCursor;
            SqlConnection conn = DeschideConexiune(workConnString);
            BugetDGV.Columns.Clear();
            LoadColumns(false);

            LoadTreeAndGrid(tnRoot, conn, ModuleInfo.CodUnitate.ToString(), BugetDGV);
            LoadRowTotalInfo(Convert.ToInt32(JurnalCB.SelectedValue), "Total");
            foreach (DataGridViewColumn col in BugetDGV.Columns)
            {
                if (col.HeaderText != "Total" && col.HeaderText != "Art./Alin.")
                    LoadRowInfo(Convert.ToDateTime(col.HeaderText), Convert.ToInt32(JurnalCB.SelectedValue), col.HeaderText);
            }
            InchideConexiune(conn);
            Cursor.Current = Cursors.Default;
            init_form = false;
        }

        private void GenereazaNC(object sender, EventArgs e)
        {
            FrmMainMdi frm = this.MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("esrp");
            if (asm == null)
                return;
            String numeClasa = "ESRP.FormulaContabilaFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                //FrmCard newFrm = asm.CreateInstance(numeClasa) as FrmCard;
                FrmWorkspace newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                    new object[] { }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmWorkspace;
                mModule.InvokeMember("GenereazaNC", BindingFlags.SetProperty, null, newFrm, new object[] { (Int16)1 });

                newFrm.MdiParent = frm;
                newFrm.Show();
            }
        }

  


    }
    [Serializable]
    public class DiviziuneMonedaSursa
    {
        public DiviziuneMonedaSursa(String nume, Int16 tag)
        {
            _Name = nume;
            _Tag = tag;
        }

        private String _Name = String.Empty;
        [System.ComponentModel.Bindable(true)]
        public String Name
        {
            get
            {
                return _Name;
            }
            set
            {
                _Name = value;
            }
        }
        private Int16 _Tag = 0;
        [System.ComponentModel.Bindable(true)]
        public Int16 Tag
        {
            get
            {
                return _Tag;
            }
            set
            {
                _Tag = value;
            }
        }

    }
}
